#include "../include/MainHeader.h"

char name[20];
FILE *fp;

int unmount_vfs(char *vfsLabel)
{

header.noOfUsedFileDescriptor=fdcounter;

nBlocks=header.maxNoOfFileDescriptor;
//printf("fdcounter= %ld\n", fdcounter);



if(ismounted!=1)
	return 4;

//printf("in unmount used fd=%d\n",header.noOfUsedFileDescriptor);
t_node* root=naryRoot;

//if(root!=NULL)
//	printf("\nroot data in unmount=%s\n",root->data->file_name);
offset=0;
fp=fopen(vfsLabel,"rb+");
if(fp==NULL)
	return 1;
else
{	fwrite(&header,sizeof(header),1,fp);	
	offset=0;
	fseek(fp,offset,SEEK_SET);
	char c;
			while(c!='#')
			{
				fread(&c,sizeof(c),1,fp);
				offset++;
			}

}

//printf("offset=%ld\n",offset );	


long int old_offset=offset;

fclose(fp);

int status=write_desc(root,vfsLabel,0);
if(status==1)
	return 1;




fclose(fp);

//printf("\nUnmounted . .!!\n");




FILE *fp1;
fp1=fopen(vfsLabel,"rb+");

fseek(fp1,old_offset,SEEK_SET);
struct FileDescriptor arrayfd3[nBlocks];
fread(arrayfd3,sizeof(struct FileDescriptor),nBlocks,fp1);


int d;

for(d=0;d<header.noOfUsedFileDescriptor;d++){
	//struct FileDescriptor *test1=(struct FileDescriptor*) malloc(sizeof(struct FileDescriptor));
	//test1=&arrayfd3[d];

	//printf("fd1 after unmounting=%s\n",arrayfd3[d].file_name);
//	printf("fd1 path after unmounting=%s\n",arrayfd3[d].path);

}




fclose(fp1);




free(naryRoot);
free(bstRoot);
free(hash);

//printf("\n-------------------End of Unmount...!!--------------\n");

//printf("noOfUsedFileDescriptor unmount= %d\n",header.noOfUsedFileDescriptor );

ismounted=0;
return 0;


}


int write_desc(t_node *root, char *filename,int count)
{

	//printf("in write desc , filename=%s\n",filename );

//	printf("%s",root->data->file_name);

	if(count==0)
	{
		strcpy(name,filename);
		fp=fopen(name,"rb+"); //enter file open mode.
		if(fp==NULL)
			return 1;
		else
		fseek(fp,offset,SEEK_SET); //set pointer of file to location where to write descriptor.
			//printf("\nroot in count 0=%s\n",root->data->file_name);
	}







	if(root!=NULL && root->is_deleted!=1)
	{
		//printf("In if\n");
		fd *f=(fd *) malloc(sizeof(fd));
		f = root->data;
		
	//	printf("value of fd= %s\n",f->file_name);
		fwrite(f, sizeof(struct FileDescriptor ), 1, fp);


	}

	if(root!=NULL)
	{
		if(root->left_child!=NULL)
	  	    write_desc(root->left_child,name,1);
	  	if(root->right_siblings!=NULL)
	    	write_desc(root->right_siblings,name,1);
    	}


}